<template>
  <div class="task-related-defects-tab">
    <div class="tab-header">
      <div class="header-info">
        <span class="defect-count">关联缺陷（{{ relatedDefects.length }}）</span>
      </div>
      <div class="header-actions">
        <el-button
          type="primary"
          size="small"
          @click="handleAddDefect"
        >
          <el-icon><Plus /></el-icon>
          添加缺陷
        </el-button>
      </div>
    </div>

    <div v-loading="loading" class="defects-list">
      <el-table
        v-if="relatedDefects.length > 0"
        :data="relatedDefects"
        size="default"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="title" label="缺陷标题" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <el-link 
              type="primary" 
              @click="handleViewDefect(row.id)"
              :underline="false"
            >
              {{ row.title }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="getStatusType(row.status)" 
              size="small"
            >
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="severity" label="严重程度" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="getSeverityType(row.severity)" 
              size="small"
            >
              {{ getSeverityName(row.severity) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="90">
          <template #default="{ row }">
            <el-tag 
              :type="getPriorityType(row.priority)" 
              size="small"
            >
              {{ getPriorityName(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="assignee_name" label="负责人" width="100" show-overflow-tooltip />
        <el-table-column prop="reporter_name" label="报告人" width="100" show-overflow-tooltip />
        <el-table-column prop="created_at" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.created_at) || '—' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              size="small"
              @click="handleViewDefect(row.id)"
            >
              查看
            </el-button>
            <el-button
              link
              type="danger"
              size="small"
              @click="handleRemoveDefect(row)"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-else description="暂无关联缺陷" :image-size="80" />
    </div>

    <!-- 缺陷选择对话框 -->
    <DefectSelectorDialog
      v-model="defectSelectorVisible"
      :project-id="projectId"
      @confirm="handleDefectSelected"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import type { Defect } from '@/api/defect'
import { formatDate } from '@/utils/date'
import { useDefectStates } from '@/composables/useDefectStates'
import { useDefectOptions } from '@/composables/useDefectOptions'
import { versionAPI } from '@/api/version'
import DefectSelectorDialog from '@/components/version/DefectSelectorDialog.vue'

interface Props {
  taskId: string
  projectId?: string
  versionIds?: string[]
}

const props = defineProps<Props>()

const emit = defineEmits<{
  (event: 'defect-updated'): void
}>()

const router = useRouter()
const loading = ref(false)
const relatedDefects = ref<Defect[]>([])
const defectSelectorVisible = ref(false)

const { getStateName, getStateColor, loadStates: loadDefectStates } = useDefectStates()
const { getSeverityName: getSeverityNameFromOptions, getPriorityName: getPriorityNameFromOptions, loadOptions: loadDefectOptions } = useDefectOptions()

const getStatusName = (status?: string) => {
  if (!status) return '未知'
  return getStateName(status)
}

const getStatusType = (status?: string) => {
  if (!status) return 'info'
  const color = getStateColor(status)
  // 根据颜色返回对应的 Element Plus tag type
  if (color.includes('green') || color.includes('success')) return 'success'
  if (color.includes('red') || color.includes('danger')) return 'danger'
  if (color.includes('orange') || color.includes('warning')) return 'warning'
  return 'info'
}

const getSeverityName = (severity?: string) => {
  if (!severity) return '未知'
  return getSeverityNameFromOptions(severity)
}

const getSeverityType = (severity?: string) => {
  if (!severity) return 'info'
  const code = severity.toLowerCase()
  if (code === 'critical' || code === 'urgent' || code === 'blocker') return 'danger'
  if (code === 'important' || code === 'major') return 'warning'
  return 'info'
}

const getPriorityName = (priority?: string) => {
  if (!priority) return '未知'
  return getPriorityNameFromOptions(priority)
}

const getPriorityType = (priority?: string) => {
  if (!priority) return 'info'
  const code = priority.toLowerCase()
  if (code === 'critical' || code === 'urgent' || code === 'blocker') return 'danger'
  if (code === 'high') return 'warning'
  if (code === 'medium') return 'success'
  return 'info'
}

const fetchRelatedDefects = async () => {
  if (!props.taskId || !props.versionIds || props.versionIds.length === 0) {
    relatedDefects.value = []
    return
  }

  loading.value = true
  try {
    // 通过版本ID查询关联的缺陷
    const allDefects: Defect[] = []
    
    for (const versionId of props.versionIds) {
      try {
        const response: any = await versionAPI.getVersionDefects(versionId, { skip: 0, limit: 100 })
        let defects: Defect[] = []
        
        if (response && response.data) {
          const data = response.data
          if (Array.isArray(data)) {
            defects = data.map((item: any) => item.defect || item).filter(Boolean)
          } else if (data.success && data.data) {
            if (Array.isArray(data.data)) {
              defects = data.data.map((item: any) => item.defect || item).filter(Boolean)
            } else if (data.data.items && Array.isArray(data.data.items)) {
              defects = data.data.items.map((item: any) => item.defect || item).filter(Boolean)
            }
          } else if (data.items && Array.isArray(data.items)) {
            defects = data.items.map((item: any) => item.defect || item).filter(Boolean)
          }
        }
        
        // 过滤出关联了当前任务的缺陷
        const taskRelatedDefects = defects.filter((defect: any) => {
          // 检查缺陷是否通过版本关联表与任务关联
          // 这里需要检查关联记录中的 task_id 是否匹配
          return defect.task_id === props.taskId || 
                 (defect.relation && defect.relation.task_id === props.taskId)
        })
        
        allDefects.push(...taskRelatedDefects)
      } catch (error) {
        console.error(`获取版本 ${versionId} 的缺陷失败:`, error)
      }
    }
    
    // 去重
    const uniqueDefects = Array.from(new Map(allDefects.map(defect => [defect.id, defect])).values())
    relatedDefects.value = uniqueDefects
  } catch (error) {
    console.error('获取关联缺陷失败:', error)
    ElMessage.error('获取关联缺陷失败')
    relatedDefects.value = []
  } finally {
    loading.value = false
  }
}

// 添加缺陷
const handleAddDefect = () => {
  defectSelectorVisible.value = true
}

// 处理缺陷选择
const handleDefectSelected = async (defects: Defect[]) => {
  if (!defects.length || !props.taskId) return

  try {
    loading.value = true
    
    // 通过版本关联缺陷
    if (props.versionIds && props.versionIds.length > 0) {
      const associatePromises = props.versionIds.map(versionId =>
        Promise.all(
          defects.map(defect =>
            versionAPI.addDefectAssociation(versionId, defect.id).catch(error => {
              console.error(`关联缺陷 ${defect.id} 到版本 ${versionId} 失败:`, error)
              return null
            })
          )
        )
      )
      await Promise.all(associatePromises)
      ElMessage.success('缺陷关联成功')
    } else {
      ElMessage.warning('请先关联版本')
      return
    }
    
    await fetchRelatedDefects()
    emit('defect-updated')
  } catch (error) {
    console.error('关联缺陷失败:', error)
    ElMessage.error('关联缺陷失败')
  } finally {
    loading.value = false
  }
}

const handleViewDefect = (defectId: string) => {
  router.push(`/defects/${defectId}`)
}

const handleRemoveDefect = async (defect: Defect) => {
  try {
    await ElMessageBox.confirm(
      `确定要移除缺陷"${defect.title}"的关联吗？`,
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 如果有版本ID，需要从版本中移除缺陷关联
    if (props.versionIds && props.versionIds.length > 0) {
      const removePromises = props.versionIds.map(versionId =>
        versionAPI.removeDefectFromVersion(versionId, defect.id).catch(error => {
          console.error(`从版本 ${versionId} 移除缺陷失败:`, error)
          return null
        })
      )
      await Promise.all(removePromises)
    }

    ElMessage.success('缺陷关联已移除')
    await fetchRelatedDefects()
    emit('defect-updated')
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('移除缺陷关联失败:', error)
      ElMessage.error('移除缺陷关联失败')
    }
  }
}

watch(() => [props.taskId, props.versionIds], () => {
  fetchRelatedDefects()
}, { immediate: true, deep: true })

onMounted(async () => {
  // 加载缺陷状态和选项数据
  await Promise.all([
    loadDefectStates(),
    loadDefectOptions()
  ])
  fetchRelatedDefects()
})
</script>

<style scoped lang="scss">
.task-related-defects-tab {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.header-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.defect-count {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.defects-list {
  min-height: 200px;
}
</style>


